package httpclint;

import java.io.IOException;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

public class ClientsMultiThreadsDemo {

	public static void main(String[] args) throws InterruptedException {
		ClientsMultiThreadsDemo d = new ClientsMultiThreadsDemo();
		d.retrive();
	}

	public void retrive() throws InterruptedException {

		ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager();

		HttpClient client = new DefaultHttpClient(cm);
		client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, new HttpHost("172.20.230.5", 3128));
		try {
			String[] urls = {
					"http://www.iteye.com/",
					"http://www.ibm.com/developerworks/cn/java/j-jtp04247.html",
					"http://www.iteye.com/topic/1118853",
					"http://vip.csdn.net/default.aspx?ZXZ=1",
					"http://caterpillar.onlyfun.net/Gossip/AlgorithmGossip/SelectionInsertionBubble.htm" };

			GetThread[] getThreads = new GetThread[urls.length];

			for (int i = 0; i < urls.length; i++) {
				getThreads[i] = new GetThread(urls[i], client, i);
			}

			for (int i = 0; i < getThreads.length; i++) {
				getThreads[i].start();
			}

			for (int i = 0; i < getThreads.length; i++) {
				getThreads[i].join();
			}
		} finally {
			client.getConnectionManager().shutdown();
		}
	}

	private static class GetThread extends Thread {
		private final HttpGet httpGet;
		private final HttpContext httpContext;
		private final HttpClient httpClient;
		private final int id;

		public GetThread(String url, HttpClient httpClient, int id) {
			super();
			this.httpGet = new HttpGet(url);
			this.httpContext = new BasicHttpContext();
			this.httpClient = httpClient;
			this.id = id;
		}

		@Override
		public void run() {
			System.out.println("Thread " + id + " is running.");
			try {
				HttpResponse res = httpClient.execute(httpGet, httpContext);
				if (res != null) {
					byte[] entity = EntityUtils.toByteArray(res.getEntity());
					System.out.println("Thread " + id + " - Entity size: "
							+ entity.length);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				httpGet.abort();
			}

		}

	}
}
